package com.fei.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
public class FileServiceImpl implements FileService{

    @Override
    public File ParentPath() {
        File file = new File("");

        try {
            File parent = file.getCanonicalFile();
            return parent;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    //异步
//    @Async        //上传最好不要用，会有一些没上传完整
    @Override
    public Boolean FileUpload(String targetPath,String fileName, MultipartFile file) {
        BufferedOutputStream out = null;
        File fileMkdir = new File(targetPath);
        fileMkdir.mkdirs();
        if(!file.isEmpty()){
            try {
                byte[] b = file.getBytes();
                out = new BufferedOutputStream(new FileOutputStream(targetPath+"//"+fileName));
                out.write(b);
                out.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public String FileSuffix(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        return suffix;
    }

    //传过来一个需要删除文件或文件夹的绝对路径
    @Async
    @Override
    public Boolean FileDelete(File file) {
        if(file.exists()){
            if(file.isFile()){
                file.delete();
            }else {
                File[] files = file.listFiles();
                for(File file1 : files){
//                    递归删除，先删除最里面的文件
                    FileDelete(file1);
                }

            }
            file.delete();
            return true;
        }
        return false;
    }


}
